# 子程序：save_data.py
import ctypes
import json

# 加载 32 位 DLL
dll_path = r"F:\pyQT\机械臂控制\lib\USBUT.dll"
dll = ctypes.CDLL(dll_path)

# 配置 USBUTParms 函数签名
USBUTParms = dll.USBUTParms
USBUTParms.argtypes = [ctypes.c_int, ctypes.c_int, ctypes.c_uint32, ctypes.c_int]
USBUTParms.restype = ctypes.c_int

# 常量定义
ISDATAREADY = 1018
GETDATA = 1019
BUFFER_LENGTH = 8191

# 数据缓冲区（使用 c_char 类型，模拟 char*）
data = (ctypes.c_char * BUFFER_LENGTH)()

try:
    # 等待数据就绪
    while not USBUTParms(ctypes.c_int(ISDATAREADY), ctypes.c_int(0), ctypes.c_uint32(0), ctypes.c_int(0)):
        pass

    # 获取数据
    # 使用 ctypes.addressof() 获取指针的内存地址并转换为 c_uint32
    receive_data_number = USBUTParms(
        ctypes.c_int(GETDATA),
        ctypes.c_int(0),
        ctypes.c_uint32(ctypes.addressof(data)),  # 转换为 unsigned int 类型的内存地址
        ctypes.c_int(BUFFER_LENGTH)  # 缓冲区大小
    )

    # 提取接收到的数据
    received_data = [data[i] for i in range(receive_data_number)]

    # 保存数据到 JSON 文件
    output_file = r"F:\pyQT\机械臂控制\data.json"
    with open(output_file, "w") as f:
        json.dump(received_data, f)
    # 打印成功消息
    print(f"Data saved to {output_file}, received {receive_data_number} items.")
    # # 测试数据
    # virtual_data = [0]
    # for i in range(1000):
    #     virtual_data.append(i%7)
    # with open(output_file, "w") as f:
    #     json.dump(virtual_data, f)
    # # 打印伪造数据
    # print(f"Data saved to {output_file}, received {virtual_data} items.")




except Exception as e:
    print(f"Error: {e}")
    exit(1)
